package cool.lichuan.framework.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.core.exceptions.UtilException;
import cool.lichuan.common.domain.Result;
import cool.lichuan.common.util.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lichuan
 * @date 2021/11/24 15:39
 * @description
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 使用hutool的Assert校验不通过异常
     *
     * @param e 异常信息
     * @return ajaxResult
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<String> assertException(IllegalArgumentException e) {
        return Result.error(e.getMessage());
    }

    /**
     * 使用hutool的UtilException
     *
     * @param e 异常信息
     * @return ajaxResult
     */
    @ExceptionHandler(UtilException.class)
    public Result<String> utilException(UtilException e) {
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(NotLoginException.class)
    public Object notLoginException(NotLoginException e, HttpServletRequest request) {
        if (ServletUtils.isAjaxRequest(request)) {
            return Result.error(HttpStatus.UNAUTHORIZED.value(), e.getMessage());
        } else {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("login");
            return modelAndView;
        }
    }
}
